module.exports = (app) => {
  const router = require("express").Router();

  //引入模型
  const mongoose = require("mongoose");
  const Article = mongoose.model("Article");
  const Category = mongoose.model("Category");
  const Hero = mongoose.model("Hero");

  //导入新闻数据
  router.get("/news/init", async (req, res) => {
    const parent = await Category.findOne({
      name: "新闻分类",
    });
    const cats = await Category.find()
      .where({
        // parent: parent,
        name: "赛事",
      })
      .lean();
    const newsTitles = [
      "2021年KPL春季赛季前赛今日开赛！重磅转会选手，新战场首秀来袭！",
      "K甲春季赛线下售票规则",
      "2021年K甲春季赛季前赛3月4日12:00开启售票，全新主场，为更强喝彩！",
      "KPL春季赛季前赛对阵公布，3月11日起每天8场比赛等你来看！",
      "2021K甲春季赛赛事日历与季前赛赛程公布",
    ];
    const newsList = newsTitles.map((title) => {
      const randomCats = cats.slice(0).sort((a, b) => Math.random() - 0.5);
      return {
        // categories: randomCats.slice(0, 2),
        categories: cats,
        title: title,
      };
    });
    // await Article.deleteMany({});
    // await Article.insertMany(newsList);
    res.send(newsList);
  });

  //获取新闻列表
  router.get("/news/list", async (req, res) => {
    // const parent = await Category.findOne({
    //   name: "新闻分类",
    // })
    //   .populate({
    //     path: "children",
    //     populate: {
    //       path: "newsList",
    //     },
    //   })
    //   .lean();
    const parent = await Category.findOne({
      name: "新闻分类",
    });
    const cats = await Category.aggregate([
      //查询条件
      { $match: { parent: parent._id } },
      {
        //联表查询
        $lookup: {
          from: "articles",
          localField: "_id",
          foreignField: "categories",
          as: "newsList",
        },
      },
      {
        //添加字段条件
        $addFields: {
          //截取5条数据
          newsList: { $slice: ["$newsList", 5] },
        },
      },
    ]);
    //在数组前面加
    const subCats = cats.map((v) => v._id);
    cats.unshift({
      name: "热门",
      newsList: await Article.find()
        .where({
          categories: { $in: subCats },
        })
        .populate("categories")
        .limit(5)
        .lean(),
    });

    cats.map((cat) => {
      cat.newsList.map((news) => {
        news.categoryName =
          cat.name == "热门" ? news.categories[0].name : cat.name;

        return news;
      });

      return cat;
    });

    res.send(cats);
  });

  //导入英雄数据
  router.get("/heroes/init", async (req, res) => {
    const rawData = [];

    for (let cat of rawData) {
      //找到当前英雄分类数据
      const category = await Category.findOne({
        name: cat.name,
      });
      //循环将分类保存在英雄里
      cat.heroes = cat.heroes.map((hero) => {
        hero.categories = [category];
        return hero;
      });
      //录入英雄
      await Hero.insertMany(cat.heroes);
    }
    res.send(await Hero.find());
  });

  //获取英雄列表
  router.get("/heroes/list", async (req, res) => {
    const parent = await Category.findOne({
      name: "英雄分类",
    });
    const cats = await Category.aggregate([
      //查询条件
      { $match: { parent: parent._id } },
      {
        //联表查询
        $lookup: {
          from: "heroes",
          localField: "_id",
          foreignField: "categories",
          as: "heroList",
        },
      },
    ]);
    //在数组前面加
    const subCats = cats.map((v) => v._id);
    cats.unshift({
      name: "热门",
      heroList: await Hero.find()
        .where({
          categories: { $in: subCats },
        })
        .limit(10)
        .lean(),
    });

    res.send(cats);
  });

  //文章详情
  router.get("/article/:id", async (req, res) => {
    const data = await Article.findById(req.params.id).lean();
    data.related = await Article.find()
      .where({
        categories: { $in: data.categories },
      })
      .limit(2);

    res.send(data);
  });

  //英雄详情
  router.get("/heroes/:id", async (req, res) => {
    const data = await Hero.findById(req.params.id)
      .populate("categories items1 items2 partners.hero")
      .lean();
    res.send(data);
  });

  app.use("/web/api", router);
};
